/*
Copyright [2020] [https://www.stylefeng.cn]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Guns采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Guns源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/stylefeng/guns-separation
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/stylefeng/guns-separation
6.若您的项目无法满足以上几点，可申请商业授权，获取Guns商业授权许可，请在官网购买授权，地址为 https://www.stylefeng.cn
 */
package cn.stylefeng.guns.sys.modular.notice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.login.SysLoginUser;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.sys.core.enums.NoticeStatusEnum;
import cn.stylefeng.guns.sys.modular.notice.entity.SysNotice;
import cn.stylefeng.guns.sys.modular.notice.entity.SysNoticeUser;
import cn.stylefeng.guns.sys.modular.notice.enums.SysNoticeExceptionEnum;
import cn.stylefeng.guns.sys.modular.notice.mapper.SysNoticeMapper;
import cn.stylefeng.guns.sys.modular.notice.mapper.SysNoticeUserMapper;
import cn.stylefeng.guns.sys.modular.notice.param.MyReceivePageReq;
import cn.stylefeng.guns.sys.modular.notice.param.NoticePageReq;
import cn.stylefeng.guns.sys.modular.notice.param.SysNoticeParam;
import cn.stylefeng.guns.sys.modular.notice.result.SysNoticeMyVO;
import cn.stylefeng.guns.sys.modular.notice.result.SysNoticeVO;
import cn.stylefeng.guns.sys.modular.notice.service.SysNoticeService;
import cn.stylefeng.guns.sys.modular.notice.service.SysNoticeUserService;
import cn.stylefeng.guns.sys.modular.org.entity.SysOrg;
import cn.stylefeng.guns.sys.modular.org.mapper.SysOrgMapper;
import cn.stylefeng.guns.sys.modular.user.result.SysUserVo;
import cn.stylefeng.guns.sys.modular.org.service.SysOrgService;
import cn.stylefeng.guns.sys.modular.user.entity.SysUser;
import cn.stylefeng.guns.sys.modular.user.mapper.SysUserMapper;
import cn.stylefeng.guns.sys.modular.user.result.SysUserResult;
import cn.stylefeng.guns.sys.modular.user.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统通知公告service接口实现类
 *
 * @author xuyuxiang
 * @date 2020/6/28 17:20
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class SysNoticeServiceImpl extends ServiceImpl<SysNoticeMapper, SysNotice> implements SysNoticeService {

    @Resource
    private SysNoticeUserMapper sysNoticeUserMapper;

    @Resource
    private SysUserService sysUserService;



    /**
     * 查询我收到的系统通知公告
     */
    @Override
    public ResponseData received(MyReceivePageReq req) {
        Long sysLoginUserId = LoginContextHolder.me().getSysLoginUserId();
        Page<SysNoticeMyVO> sysNoticeMyVOPage = baseMapper.received(PageFactory.defaultPage(), sysLoginUserId,req.getNoticeType(),req.getReadStatus());
        PageResult<SysNoticeMyVO> sysNoticeMyVOPageResult = new PageResult<>(sysNoticeMyVOPage);
        return ResponseData.success(sysNoticeMyVOPageResult);
    }

    @Override
    public List<SysNoticeVO> noticeInfo() {

        List<SysNoticeVO> sysNoticeVO = baseMapper.noticeInfo();
        return sysNoticeVO;
    }

    @Override
    public SysNoticeVO selectNoticeById(Long noticeId) {
        return baseMapper.selectNoticeById(noticeId);
    }

    /**
     * 查询系统公告分页信息
     * @param
     * @return
     */

    @Override
    public ResponseData page(NoticePageReq noticePageReq) {
        Page<SysNoticeVO> page = baseMapper.page(PageFactory.defaultPage(), noticePageReq.getNoticeType(), noticePageReq.getStatus());
        return ResponseData.success(new PageResult<>(page));
    }
    @Autowired
    private  SysNoticeUserService sysNoticeUserService;

    @Autowired
    private  SysOrgMapper sysOrgMapper;

    /**
     * 添加公告
     * @param noticePageReq 添加参数
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(NoticePageReq noticePageReq) {

        SysNotice sysNotice = new SysNotice();
        BeanUtil.copyProperties(noticePageReq, sysNotice);
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        sysNotice.setPublicUserId(sysLoginUser.getId());
        sysNotice.setPublicUserName(sysLoginUser.getName());
        sysNotice.setPublicOrgId(sysLoginUser.getLoginEmpInfo().getOrgId());
        sysNotice.setPublicOrgName(sysLoginUser.getLoginEmpInfo().getOrgName());

        //如果是发布，则设置发布时间
        if (NoticeStatusEnum.PUBLIC.getCode().equals(sysNotice.getStatus())) {
            sysNotice.setPublicTime(new Date());
        }

        if (noticePageReq.getNoticeType() == 1) {
            String orgIds = noticePageReq.getOrgIds();
            List<Long> longList = new ArrayList<>();
            if (orgIds != null && !orgIds.equals("")) {
                List<String> list = Arrays.asList(orgIds.split(","));
                for (String s : list) {
                    List<SysUserVo> sysUserVos = sysUserMapper.userList(Long.valueOf(s));
                    for (SysUserVo sysUserVo : sysUserVos) {
                        if (ObjectUtil.isNotNull(sysUserVo)) {
                            longList.add(sysUserVo.getId());
                        }
                    }
                }
            }

            String str = longList.stream().map(integer -> integer.toString()).collect(Collectors.joining(","));
            sysNotice.setNoticeUserIds(str);
            sysNotice.setNoticeOrgIds(noticePageReq.getOrgIds());
        } else {
            Set<Long> longSet = new HashSet<>();
            String userIds = noticePageReq.getNoticeUserIds();
            if (userIds != null && !userIds.equals("")) {
                List<String> list = Arrays.asList(userIds.split(","));
                for (String s : list) {
                    SysUserResult sysUserResult = sysUserMapper.selectUserById(Long.valueOf(s));
                    if (ObjectUtil.isNotNull(sysUserResult)) {
                        longSet.add(sysUserResult.getOrgId());
                    }
                }
            }
            sysNotice.setNoticeUserIds(userIds);
            String str = longSet.stream().map(integer -> integer.toString()).collect(Collectors.joining(","));
            sysNotice.setNoticeOrgIds(str);
        }
        this.save(sysNotice);
    }
    /**
     * 添加用户已读公告
     */
    private  void  readNotice(NoticePageReq noticePageReq) {
        Long loginUserId = LoginContextHolder.me().getSysLoginUserId();
            if (noticePageReq.getNoticeUserIds().contains(loginUserId.toString())) {
                sysNoticeUserService.add(noticePageReq.getId(), loginUserId);
        }
    }



    /**
     * 系统公告发布（删除 草稿 撤回）
     * @param sysNoticeParam 删除参数
     */

    @Override
    public void delete(SysNoticeParam sysNoticeParam) {
        Long sysLoginUserId = LoginContextHolder.me().getSysLoginUserId();
        SysNotice sysNotice = baseMapper.selectById(sysNoticeParam.getId());
        sysNotice.setUpdateUser(sysLoginUserId);
        int i = baseMapper.updateById(sysNotice);
        if (i == 0){
            throw new ServiceException(SysNoticeExceptionEnum.NOTICE_CANNOT_DELETE);
        }
    }

    /**
     * 编辑通告信息
     * @param noticePageReq 编辑参数
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(NoticePageReq noticePageReq) {

        SysNotice sysNotice = baseMapper.selectById(noticePageReq.getId());
        if (ObjectUtil.isNull(sysNotice)){
            throw new ServiceException(SysNoticeExceptionEnum.NOTICE_NOT_EXIST);
        }

        //非草稿状态
        Integer status = sysNotice.getStatus();
        if (!NoticeStatusEnum.DRAFT.getCode().equals(status)) {
            throw new ServiceException(SysNoticeExceptionEnum.NOTICE_CANNOT_EDIT);
        }
        Long loginUserId = LoginContextHolder.me().getSysLoginUserId();
        sysNotice.setStatus(noticePageReq.getStatus());
        //修改用户
        sysNotice.setUpdateUser(loginUserId);
        sysNotice.setNoticeType(noticePageReq.getNoticeType());
        sysNotice.setContent(noticePageReq.getContent());
        sysNotice.setTitle(noticePageReq.getTitle());
        sysNotice.setUpdateTime(new Date());
        //如果是发布，则设置发布时间
        if (NoticeStatusEnum.PUBLIC.getCode().equals(sysNotice.getStatus())) {
            sysNotice.setPublicTime(new Date());
        }
        if (noticePageReq.getNoticeType() == 1) {
            String orgIds = noticePageReq.getOrgIds();
            List<Long> longList = new ArrayList<>();
            if (orgIds != null && !orgIds.equals("")) {
                List<String> list = Arrays.asList(orgIds.split(","));
                for (String s : list) {
                    List<SysUserVo> sysUserVos = sysUserMapper.userList(Long.valueOf(s));
                    for (SysUserVo sysUserVo : sysUserVos) {
                        if (ObjectUtil.isNotNull(sysUserVo)) {
                            longList.add(sysUserVo.getId());
                        }
                    }
                }
            }

            String str = longList.stream().map(integer -> integer.toString()).collect(Collectors.joining(","));
            sysNotice.setNoticeUserIds(str);
            sysNotice.setNoticeOrgIds(noticePageReq.getOrgIds());
        } else {
            Set<Long> longSet = new HashSet<>();
            String userIds = noticePageReq.getNoticeUserIds();
            if (userIds != null && !userIds.equals("")) {
                List<String> list = Arrays.asList(userIds.split(","));
                for (String s : list) {
                    SysUserResult sysUserResult = sysUserMapper.selectUserById(Long.valueOf(s));
                    if (ObjectUtil.isNotNull(sysUserResult)) {
                        longSet.add(sysUserResult.getOrgId());
                    }
                }
            }
            sysNotice.setNoticeUserIds(userIds);
            String str = longSet.stream().map(integer -> integer.toString()).collect(Collectors.joining(","));
            sysNotice.setNoticeOrgIds(str);
        }
        this.updateById(sysNotice);


    }
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private  SysUserMapper sysUserMapper;
    @Override
    public SysNoticeVO detail(Long noticeId) {
        SysNoticeVO sysNoticeVO = baseMapper.detail(noticeId);
        if (ObjectUtil.isNull(sysNoticeVO)) {
            throw new ServiceException(SysNoticeExceptionEnum.NOTICE_NOT_EXIST);
        }
        List<String> orglist = Arrays.asList(sysNoticeVO.getNoticeOrgIds().split(","));
        List<String> userlist = Arrays.asList(sysNoticeVO.getNoticeUserIds().split(","));
        sysNoticeVO.setUserIdList(userlist);
        sysNoticeVO.setOrgIdList(orglist);

        //添加系统用户已读公告
            Long loginUserId = LoginContextHolder.me().getSysLoginUserId();
            List<SysNoticeUser> sysNoticeUsers = sysNoticeUserMapper.selectList(new QueryWrapper<SysNoticeUser>().lambda().eq(SysNoticeUser::getNoticeId, noticeId
            ).eq(SysNoticeUser::getUserId, loginUserId));
            if (ObjectUtil.isEmpty(sysNoticeUsers)) {
                SysNotice sysNotice = baseMapper.selectById(noticeId);
                NoticePageReq noticePageReq = new NoticePageReq();
                noticePageReq.setId(noticeId);
                noticePageReq.setNoticeUserIds(sysNotice.getNoticeUserIds());
                noticePageReq.setOrgIds(sysNotice.getNoticeOrgIds());

                readNotice(noticePageReq );
            }


        return sysNoticeVO;
    }

    /**
     *修改状态
     * @param sysNoticeParam 修改参数
     */
    @Override
    public void changeStatus(SysNoticeParam sysNoticeParam) {
        if (ObjectUtil.isNotNull(sysNoticeParam)){
            SysNotice sysNotice = baseMapper.selectById(sysNoticeParam.getId());
            if (ObjectUtil.isNull(sysNotice)){
                throw new ServiceException(SysNoticeExceptionEnum.NOTICE_NOT_EXIST);
            }
            sysNotice.setStatus(sysNoticeParam.getStatus());
            baseMapper.updateById(sysNotice);
        }
    }




    /**
     * 获取系统通知公告
     *
     * @author xuyuxiang
     * @date 2020/6/29 9:58
     */
    private SysNotice querySysNotice( Long noticeId) {
        SysNotice sysNotice = this.getById(noticeId);
        if (ObjectUtil.isNull(sysNotice)) {
            throw new ServiceException(SysNoticeExceptionEnum.NOTICE_NOT_EXIST);
        }
        return sysNotice;
    }
    /**
     * 获取系统发布公告
     *
     * @author xuyuxiang
     * @date 2020/6/29 9:58
     */

    @Override
    public List<SysNoticeVO> noticeList() {


        return null
                ;
    }
}
